package com.xueqi.servlet;

import com.xueqi.bean.EbookCategory;
import com.xueqi.bean.EbookEntry;
import com.xueqi.service.EbookCategoryService;
import com.xueqi.service.EbookEntryService;
import com.xueqi.service.impl.EbookCategoryServiceImpl;
import com.xueqi.service.impl.EbookEntryServiceImpl;
import com.xueqi.utils.DateUtils;
import com.xueqi.utils.PageUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet(name = "EntryServlet",urlPatterns = "/entry")
public class EntryServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //1.接收参数
        String method = request.getParameter("method");
        //2.调取方法->使用反射的方式简化（读取的method的值就表示所要访问的方法名）
        try {
            //通过反射得到对应的方法对象
            Class cla = this.getClass();
            //getDeclaredMethod(被反射的方法名，被反射的方法的参数列表-Class)
            Method method1 = cla.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //执行该方法 invoke(执行该方法的对象，该方法的实参)
            method1.invoke(this,request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
        /*if("delete".equals(method)){
            delete(request, response);
        }else if ("add".equals(method)){
            add(request, response);
        }else if ("findbyid".equals(method)){
            findbyid(request,response);
        }else if("gettypes".equals(method)){
            gettypes(request,response);
        }else if ("update".equals(method)){
            update(request, response);
        }else{
            selectall(request, response);
        }*/
        }
    //自定义新增方法
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.接收参数
        String bookname = request.getParameter("bookname");
        String booktype = request.getParameter("booktype");
        String content = request.getParameter("content");
        String username = request.getParameter("username");
        String time = request.getParameter("time");

        //2.调取service方法
        EbookEntryService entryService = new EbookEntryServiceImpl();
        EbookEntry entry = new EbookEntry();
        entry.setCategoryid(Integer.parseInt(booktype));
        entry.setTitle(bookname);
        entry.setSummary(content);
        entry.setUploaduser(username);
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date=format.parse(time);
            entry.setCreatedate(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = entryService.addBook(entry);
        //3.跳转页面
        if (i>0){
            response.sendRedirect("/entry");
        }else{
            response.sendRedirect("/add.jsp");
        }
    }
    //自定义删除方法
    public void delete(HttpServletRequest request, HttpServletResponse response){
        String tid = request.getParameter("tid");
        EbookEntryServiceImpl service = new EbookEntryServiceImpl();
        int i = service.DeleteBook(Integer.parseInt(tid));
        try {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            if(i>0){
                out.write("<script>alert('删除成功');location.href='/entry'</script>");
            }else {
                out.write("<script>alert('删除失败');location.href='/entry'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void findbyid(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        String tid = request.getParameter("tid");
        EbookEntryServiceImpl service = new EbookEntryServiceImpl();
        EbookEntry entry = service.findbyid(Integer.parseInt(tid));
        request.setAttribute("entry",entry);
        EbookCategoryServiceImpl categoryService = new EbookCategoryServiceImpl();
        List<EbookCategory> categoryList = categoryService.findtypes();
        request.setAttribute("typelist",categoryList);
        request.getRequestDispatcher("/update.jsp").forward(request,response);

    }
    public  void gettypes(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        //1.接收参数
        //2.调取sercice方法
        EbookCategoryService service=new EbookCategoryServiceImpl();
        List<EbookCategory> list=service.findtypes();
        //3.跳转页面
        request.setAttribute("types",list);
        request.getRequestDispatcher("/add.jsp").forward(request,response);
    }
    public void update(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        String id = request.getParameter("id");
        String bookname = request.getParameter("bookname");
        String content = request.getParameter("content");
        String type=request.getParameter("type");
        String username = request.getParameter("username");
        String time = request.getParameter("time");
        EbookEntryServiceImpl service = null;
        EbookEntry entry = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format.parse(time);
            service = new EbookEntryServiceImpl();
            entry = new EbookEntry(Integer.parseInt(id),Integer.parseInt(type),bookname,content,username,date,null);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = service.UpdateBook(entry);
        if (i>0){
            response.sendRedirect("/entry");
        } else {
            response.sendRedirect("/entry?method=findbyid&tid="+id);
        }
    }
    public void selectall(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.获取参数
        String typeid = request.getParameter("typeid");//模糊查询条件
        //接收页码值
        String index = request.getParameter("index");
        //2.调取service方法
        EbookEntryService service=new EbookEntryServiceImpl();
        int tid=0;
        if(typeid!=null){
            tid=Integer.parseInt(typeid);
        }
        int pageindex=1;
        if(index!=null){
            pageindex=Integer.parseInt(index);
        }
        List<EbookEntry> list= service.findall(tid,pageindex, DateUtils.PAGESIZE);

        //查询分类列表的方法
        EbookCategoryServiceImpl categoryService = new EbookCategoryServiceImpl();
        List<EbookCategory> categoryList = categoryService.findtypes();
        //查询总条数，通过总条数算出总页数
        int totalcount = service.totalcount(tid);
        //将模糊查询的条件值重新保存
        request.setAttribute("categorytid",tid);//存模糊查询的条件
        request.setAttribute("typelist",categoryList);


       /* request.setAttribute("booklist",list);
        request.setAttribute("pageindex",pageindex);
        request.setAttribute("count",totalcount);//总条数
        request.setAttribute("pages",totalpage);//总页数*/
        PageUtils<EbookEntry> pageUtil= new PageUtils<>();
        pageUtil.setPageIndex(pageindex);
        pageUtil.setTotalCount(totalcount);
        pageUtil.setDataList(list);
        request.setAttribute("p1",pageUtil);
        //3.跳转页面
        request.getRequestDispatcher("/show.jsp").forward(request,response);
    }
}
